﻿using System.IO;

namespace Fetches.Fetch.Utils
{
    public class BinaryFormatterHelper
    {
        /// <summary>
        /// 可以将闭包的函数序列化传递出去,只支持.NetFramework不支持.NetCore
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] ToBinary<T>(T obj)
        {
            using (var stream = new MemoryStream())
            {
                new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Serialize(stream, obj);
                return stream.ToArray();
            }
        }

        public static T FromBinary<T>(byte[] data)
        {
            using (var stream = new MemoryStream(data))
            {
               var obj= new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Deserialize(stream);
                return (T)obj;
            }
        }
    }
}
